'''
    Goblinoid: Experience all of MediaGoblin on an Android Device
    Copyright (C) 2015 Dylan Jeffers

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
'''

from __future__ import print_function

from kivy.app import App
from kivy.core.window import Window
from kivy.utils import platform
from pypump.exception import PyPumpException
from goblinoid.services.login_service import user_logged_on, load_user
from goblinoid.services.pump_service import PumpService
from goblinoid.root.goblinscreenmanager import GoblinScreenManager

if platform() == 'android':
    from jnius import autoclass
    from jnius import cast

__version__ = '0.1.3-alpha7'


class MediaGoblinApp(App):

    def build(self, **kwargs):
        self.user_dir = self.get_user_dir()
        self.pump_service = PumpService()
        self.sm = self.init_screen_manager()
        # NOTE: this is a poor hotfix to avoid the common
        # PyPumpException.
        if user_logged_on(self.user_dir):
            try:
                pump = load_user(self.user_dir)
                self.pump_service.pump = pump
                self.open_view('action', False)
            except PyPumpException, e:
                print('Error: {0}, trying once more...'.format(e))
                # NOTE: eventually add a toast to alert user of issue
                try:
                    pump = load_user(self.user_dir)
                    self.pump_service.pump = pump
                    self.open_view('action', False)
                except PyPumpException, e:
                    print('Error: {0}, transitioning to login'.format(e))
                    self.open_view('login', True)
        else:
            self.open_view('login', False)

        self.bind(on_start=self.post_build_init)
        return self.sm

    def init_screen_manager(self):
        from goblinoid.root.screenprovider import ScreenManagerProvider
        from goblinoid.root.screenstack import ScreenStack
        from goblinoid.root.screenprovider import LoginProvider, ActionProvider

        screen_providers = dict([
            ('login', (LoginProvider, 1)),
            ('action', (ActionProvider, 2))
            ])
        screen_provider = ScreenManagerProvider(
            screen_providers=screen_providers)
        return RootScreenManager(
            screen_stack=ScreenStack(),
            screen_provider=screen_provider)

    def post_build_init(self, ev):
        if platform == 'android':
            Window.softinput_mode = 'below_target'
        win = self._app_window
        win.bind(on_keyboard=self._key_handler)

    def _key_handler(self, *args):
        key = args[1]
        if key in (1000, 27):
            self.dispatch_event('on_back_pressed')
            return True

    def update_pump_service(self, pump):
        self.pump_service.update_pump(pump)

    def open_view(self, class_name, previous):
        if self.sm.current_screen is None:
            self.sm.open_screen(class_name=class_name, name=class_name)
        else:
            self.sm.replace_screen(class_name=class_name, name=class_name)

    def get_pump_service(self):
        print('printing the pump model: {0}'.format(self.pump_service))
        return self.pump_service

    def on_pause(self):
        return True

    def on_resume(self):
        pass

    def dispatch_event(self, event, **kwargs):
        result = self.sm.current_screen.dispatch(event, **kwargs)
        self.handle_dispatch_result(event, result)

    def handle_dispatch_result(self, event, result):
        if event == 'on_back_pressed':
            if not result:
                self.send_app_to_background()

    def send_app_to_background(self):
        if platform == 'android':
            PythonActivity = autoclass('org.renpy.android.PythonActivity')
            Intent = autoclass('android.content.Intent')
            intent = Intent()
            intent.setAction(Intent.ACTION_MAIN)
            intent.addCategory(Intent.CATEGORY_HOME)
            currentActivity = cast(
                'android.app.Activity',
                PythonActivity.mActivity)
            currentActivity.startActivity(intent)
        else:
            App.get_running_app().stop()

    def get_user_dir(self):
        if platform == 'android':
            from jnius import autoclass, cast
            PythonActivity = autoclass('org.renpy.android.PythonActivity')
            current_activity = cast('android.app.Activity', PythonActivity.mActivity)
            user_dir = current_activity.getApplicationContext().getFilesDir().getPath()
            return user_dir
        else:
            return self.user_data_dir


class RootScreenManager(GoblinScreenManager):
    pass

if __name__ == '__main__':
    MediaGoblinApp().run()
